/**
 * @description http模块
 */
// import localeConfig from '@/configs/locale'
import signConfig from '@/configs/sign'
import { jumpToLogin } from '@/utils/utils'
import { cso } from '@/utils/sign'

// 接口基地址
const BASE_URL = import.meta.env.VITE_BASE_URL
// GET请求方法
const METHOD_GET = 'GET'

// 请求拦截器
const requestInterceptor = (config) => {
  const localeLang = useLocale()
  const headers = {}

  if (config.options.method?.toLocaleUpperCase() === METHOD_GET) {
    // GET请求
    config.options.params = cso(config.options.params || {}, signConfig.ak)
  } else {
    // POST请求
    const body = cso(config.options.body || {}, signConfig.ak)
    const formData = new FormData()
    Object.keys(body)?.forEach((key) => {
      body[key] && formData.append(key, body[key])
    })
    config.options.body = formData
  }

  if (config.options.meta?.needAuth) {
    const { getToken, getUid } = useAuth()
    const token = getToken()
    const uid = getUid()

    headers['uid'] = uid
    headers['token'] = token
  }

  // TODO国际化功能语言类型先写死
  // headers['cb-lang'] = localeConfig[localeLang.value]
  headers['cb-lang'] = 'zh-CN'

  config.options.headers = headers

  return config
}

// 响应拦截器
const responseInterceptor = (response) => {
  const res = response.response
  // 将code状态码转成Number类型
  res._data?.code && (res._data.code = Number(res._data.code))

  if (res._data.status === 200) {
    return response
  } else if (res._data.status === 401) {
    // token过期或失效
    const { removeToken, removeUid } = useAuth()
    const userInfo = useUserInfo()
    removeToken()
    removeUid()
    // 清空用户信息
    userInfo.value = {}

    // 当前接口需要权限的话，登录失效即跳转登录页
    jumpToLogin()

    return Promise.reject(res._data)
  } else if (res._data.status === 400) {
    return Promise.reject(res._data)
  }
  return Promise.reject(res._data)
}

// 错误拦截器
const errorInterceptor = (err) => {
  return Promise.reject(err.error)
}

const httpInstance = $fetch.create({
  baseURL: BASE_URL,
  onRequest: requestInterceptor,
  onResponse: responseInterceptor,
  onRequestError: errorInterceptor
})

export default httpInstance
